<template>
  <div class="content-div">
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <!-- <div class="clear-msg">
        <span @click="clearMsg">清除未读消息</span>
      </div> -->
      <div class="msg-item-box" @click="toPage('/msgDetail', {type: '1', have_no_read: sysNoRead > 0 ? 1 : 0})">
        <van-badge :dot="sysNoRead > 0 ? true : false">
          <img src="@/assets/images/icon-msg.png" alt="" srcset="">
        </van-badge>
        <div class="msg-content-box">
          <div class="msg-name-box">
            <span>系统消息</span>
            <span>{{sysMsgList && sysMsgList.length ? sysMsgList[0].createTime : ''}}</span>
          </div>
          <span class="msg-content">{{sysMsgList && sysMsgList.length ? sysMsgList[0].content : '暂时没有新的消息哦~'}}</span>
        </div>
      </div>
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
        <div @click="toPage('/msgDetail', {type: '2', accompanying_physician_id: item.accompanying_physician_id, have_no_read: item.noReadNum > 0 ? 1 : 0, wid: item.wid, accompanyingHeadSculpture: item.accompanyingHeadSculpture})" class="msg-item-box" v-for="(item, index) in list" :key="index">
          <van-badge :dot="item.noReadNum > 0 ? true : false">
            <img :src="item.accompanyingHeadSculpture" alt="" srcset="">
          </van-badge>
          <div class="msg-content-box">
            <div class="msg-name-box">
              <span>{{item.accompanyingPhysicianName}}</span>
              <span>{{item.createTime}}</span>
            </div>
            <span class="msg-content">{{item.content}}</span>
          </div>
        </div>
      </van-list>
    </van-pull-refresh>
    <!-- <instant-message></instant-message> -->
  </div>
</template>
<script>
// import instantMessage from '@/components/instant-message/index.js'
// import WebsocketData from '@/components/stock-camera'
import { Toast } from 'vant'
import { selectNotificationMessageNewList, getNotificationMessageNewSys, selectIsReadeList } from '@/api/medical.js'
export default {
  name: 'index',
  data () {
    return {
      isLoading: false,
      loading: false,
      finished: false,
      list: [],
      pageParam: {
        pageSize: 20,
        pageNo: 1
      },
      sysNoRead: 0,
      sysMsgList: [],
      // socket参数
      socket: null,
      timeout: 15000, // 15秒一次心跳
      timeoutObj: null, // 心跳心跳倒计时
      serverTimeoutObj: null, // 心跳倒计时
      timeoutnum: null, // 断开 重连倒计时
      lockReconnect: false, // 防止
      websocket: null
    }
  },
  components: {
    // instantMessage
  },
  created () {
    // ws等同于http，wss等同于https
    // let wsUrl = 'ws://accompaniment.lngov.top/api/websocket/?sid=123123' // websocket链接地址
    // this.websocket = new WebSocket(wsUrl)
    // this.websocket.onopen = this.websocketonopen
    // this.websocket.onerror = this.websocketonerror
    // this.websocket.onmessage = this.setOnmessageMessage
    // this.websocket.onclose = this.websocketclose
  },
  methods: {
    getSysMsg () { // 系统消息
      getNotificationMessageNewSys({
        type: '1',
        member_id: this.$store.state.user.token
        // is_accompanying_read: '1'
      }).then(res => {
        if (res.data.errcode === 0 && res.data.data && res.data.data.id) {
          this.sysMsgList[0] = res.data.data
          console.log(this.sysMsgList, 'this.sysMsgList')
        }
      })
    },
    getIsMsg () {
      selectIsReadeList({
        member_id: this.$store.state.user.token,
        userType: '1',
        is_accompanying_read: '1'
      }).then(res => {
        if (res.data.errcode === 0) {
          this.sysNoRead = res.data.data[0].isRead
        }
      })
    },
    toPage (path, query) {
      this.$router.push({
        path,
        query
      })
    },
    onLoad () {
      selectIsReadeList({
        member_id: this.$store.state.user.token,
        userType: '2'
      }).then(res => {
        if (res.data.errcode === 0) {
          selectNotificationMessageNewList({
            member_id: this.$store.state.user.token,
            // type: '3',
            ...this.pageParam
          }).then(ret => {
            if (ret.data.errcode === 0) {
              ret.data.data.results.forEach(item => {
                res.data.data.forEach(hmsg => {
                  if (hmsg.accompanying_physician_id === item.accompanying_physician_id) {
                    item.noReadNum = hmsg.isRead
                  }
                })
              })
              this.list = this.list.concat(ret.data.data.results)
              this.loading = false
              if (ret.data.data.results.length <= 0 || ret.data.data.results.length < this.pageParam.pageSize) {
                this.finished = true
              }
              this.pageParam.pageNo += 1
            }
          })
        }
      })
    },
    clearMsg () {
      console.log(1)
    },
    onRefresh () {
      setTimeout(() => {
        Toast('刷新成功')
        this.isLoading = false
      }, 1000)
    },
    acceptMsg (event) {
      console.log(event, '消息页面获取服务器返回的数据')
    },
    initWebSocket () {
      let that = this
      if (window.WebSocket) {
        // ws等同于http，wss等同于https
        let wsUrl = `ws://accompaniment.lngov.top/api/websocket/?sid=${this.$store.state.user.token}` // websocket链接地址
        that.websocket = new WebSocket(wsUrl)
      }
      that.websocket.onopen = that.websocketonopen
      that.websocket.onerror = that.websocketonerror
      that.websocket.onmessage = that.setOnmessageMessage
      that.websocket.onclose = that.websocketclose
    },
    websocketonopen () {
      // 开启心跳
      this.start()
    },
    start () {
      // 清除延时器
      console.log('WebSocket连接成功')
      this.timeoutObj && clearTimeout(this.timeoutObj)
      this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj)
      this.timeoutObj = setTimeout(() => {
        if (this.websocket && this.websocket.readyState == 1) {
          var data = { 'code': 2, 'msg': '心跳', 'data': '心跳' }
          this.websocket.send(JSON.stringify(data)) // 给服务端定时发送消息，保持链接
        } else {
          this.reconnect()
        }
        // 定义一个延时器等待服务器响应，若超时，则关闭连接，重新请求server建立socket连接
        this.serverTimeoutObj = setTimeout(() => {
          this.websocket.close()
        }, this.timeout)
      }, this.timeout)
    },
    reset () { // 重置心跳
      // 清除时间
      clearTimeout(this.timeoutObj)
      clearTimeout(this.serverTimeoutObj)
      // 重启心跳
      this.start()
    },
    // 重新连接
    reconnect () {
      console.log('重连')
      if (this.lockReconnect) return
      this.lockReconnect = true
      // 没连接上会一直重连，设置延迟避免请求过多
      this.timeoutnum && clearTimeout(this.timeoutnum)
      this.timeoutnum = setTimeout(() => {
        this.initWebSocket()
        this.lockReconnect = false
      }, 2000)
    },
    // 监听消息(接收服务端返回的数据)
    async setOnmessageMessage (event) {
      console.log(event, '服务器返回的数据')
      this.reset()
      // 自定义全局监听事件
      window.dispatchEvent(new CustomEvent('onmessageWS', {
        detail: {
          data: event.data
        }
      }))
      // let message = JSON.parse(event.data)
      // this.list.push(message)
    },
    websocketonerror (e) {
      console.log('WebSocket连接发生错误' + e)
    },
    websocketclose (e) {
      this.websocket.close()
      clearTimeout(this.timeoutObj)
      clearTimeout(this.serverTimeoutObj)
      console.log('WebSocket连接关闭')
      // websocket关闭后重新尝试连接,保持心跳
      setTimeout(() => {
        this.reconnect()
      }, 5000)
    },
    websocketsend (messsage) {
      this.websocket.send(messsage)
    },
    closeWebSocket () { // 关闭websocket
      this.websocket.close()
    }
  },
  mounted () {
    this.getIsMsg()
    this.getSysMsg()
    // this.initWebSocket()
    // this.createSseConnect()
  }
}
</script>

<style scoped lang="less">
  .content-div{
    font-size: 12px;
    background-color: #FFFFFF;
    min-height: 100%;
    background-image: url('../../../../assets/images/bg.png');
    background-repeat: no-repeat;
    background-size: 100% auto;
    .clear-msg{
      height: 34px;
      text-align: right;
      line-height: 34px;
      padding-right: 10px;
    }
    .msg-item-box{
      width: 300px;
      margin-left: 10px;
      border-bottom: 1px solid #F8F8F8;
      box-sizing: border-box;
      padding: 15px 10px;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      position: relative;
      img{
        width: 36px;
        height: 36px;
        border-radius: 50%;
      }
      .msg-content-box{
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
        align-items: flex-start;
        width: calc(100% - 46px);
        margin-left: 10px;
        .msg-name-box{
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          align-items: center;
          width: 100%;
          span:last-child{
            font-size: 10px;
          }
        }
        .msg-content{
          width: 100%;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          word-break: break-all;
          padding-top: 4px;
        }
      }
    }
  }
</style>
